const path = require('path')
const fs = require('fs')

const logs = require('./log')
const { get, set, merge, escapeRegExp } = require('lodash')

const utils = {
    get,
    set,
    merge,
    escapeRegExp,
    sleep (t = 0) {
        return new Promise(resolve => {
            setTimeout(resolve, t)
        })
    },

    getDate() {
        const date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()
        const hour = date.getHours()
        const minute = date.getMinutes()
        const second = date.getSeconds()
        return year + '年' + month + '月' + day + '日 ' + hour + ':' + minute + ':' + second
    },

    isFile (file, cwd = global.PRESET_PATH) {
        try {
            return fs.statSync(path.join(cwd, file)).isFile()
        } catch (e) {
            return false
        }
    },

    isDirectory (file, cwd = global.PRESET_PATH) {
        try {
            return fs.statSync(path.join(cwd, file)).isDirectory()
        } catch (e) {
            return false
        }
    },

    hasFile(file, cwd = global.PRESET_PATH) {
        return fs.existsSync(path.join(cwd, file))
    },

    getFileData(file, cwd = global.PRESET_PATH) {
        try {
            const data = fs.readFileSync(path.join(cwd, file), 'utf8')
            return data
        } catch (e) {
            // TODO 出错了
            logs.error('未找到此文件：' + file, 'error')
            return false
        }
    },

    async writeFileData(file, data, cwd = global.PRESET_PATH) {
        return new Promise(async (resolve) => {
            try {
                fs.writeFileSync(path.join(cwd, file), data)
                resolve(true)
            } catch (e) {
                // TODO 出错了
                logs.error('读取文件出错：' + file)
                resolve(false)
            }
        })
    },

    mkDirsSync (dirname, cwd = global.PRESET_PATH, isInit = true) {
        if (isInit) {
            dirname = path.resolve(cwd, dirname)
        }
        if (fs.existsSync(dirname)) {
            return true
        } else {
            if (utils.mkDirsSync(path.dirname(dirname), cwd, false)) {
                try {
                    fs.mkdirSync(dirname, { recursive: true })
                } catch (e) {}
                return true
            }
        }
    }
}

module.exports = utils
